package com.pp.small.auth.controller;

import com.pp.small.api.user.bo.UserBo;
import com.pp.small.api.user.client.UserFeignClient;
import com.pp.small.auth.bo.TokenInfo;
import com.pp.small.auth.dto.LoginParam;
import com.pp.small.common.base.BaseResult;
import com.pp.small.common.constants.SecurityConstants;
import com.pp.small.common.enums.ResponseEnum;
import com.pp.small.common.utils.IdUtils;
import com.pp.small.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserFeignClient userFeignClient;

    @PostMapping("/login")
    public BaseResult<TokenInfo> login(@RequestBody LoginParam param) {
        log.info("登录: {}", param);
        BaseResult<UserBo> ret = userFeignClient.getUserByUserName(param.getUserName());
        if (!ret.isSuccess()) {
            return BaseResult.fail(ResponseEnum.UNAUTHORIZED);
        }

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, IdUtils.fastUUID());
        claimsMap.put(SecurityConstants.USER_ID, ret.getData().getId());
        claimsMap.put(SecurityConstants.USER_NAME, ret.getData().getName());

        // 返回token信息
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setAccessToken(JwtUtils.createToken(claimsMap));
        return BaseResult.success(tokenInfo);
    }
}
